
import Clipboard from 'clipboard'

//获取页面传参值
function getQueryString(name) {
	var result = window.location.search.match(new RegExp("[\?\&]" + name + "=([^\&]+)", "i"));
	console.log(result)
	if (result == null || result.length < 1) {
		console.log("ERR: 页面参数为空");
		return "";
	}
	return result[1];
};
// 两个时间戳的相减 并返回多少天 多少小时 多少秒
function reduceTime(stime){
	let startime = Number(stime)
	let nowTime = new Date().getTime()
	let temp = (nowTime - startime)/1000
	return temp
}
//下载并更新app
function updateApp(wgtUrl, force) {
	if (!force) {
		plus.nativeUI.showWaiting("下载最新应用...");
	}
	plus.downloader.createDownload(wgtUrl, {
		filename: "_doc/update/"
	}, function(d, status) {
		if (status == 200) {
			if (!force) {
				install(d.filename);
			} else {
				plus.nativeUI.alert("最新版本已下载，请安装更新！", function() {
					install(d.filename);
				}, "版本更新", "更新");
			}
		} else {
			plus.nativeUI.alert("下载失败！");
		}
		plus.nativeUI.closeWaiting();
	}).start();
}
// 复制文字
function handleClipboard (text, event, onSuccess, onError) {
	  event = event || {}
	  const clipboard = new Clipboard(event.target, {
		text: () => text
	  })
	  clipboard.on('success', () => {
		onSuccess()
		clipboard.off('error')
		clipboard.off('success')
		clipboard.destroy()
	  })
	  clipboard.on('error', () => {
		onError()
		clipboard.off('error')
		clipboard.off('success')
		clipboard.destroy()
	  })
	  clipboard.onClick(event)
}
//安装资源文件
function install(path) {
	plus.runtime.install(path, {}, function() {

	}, function(e) {

	});
}

//格式化日期
function formatDate(n, t) {
	var i, r, u;
	if (!n)
		return "";
	i = n;
	typeof n == "string" && (i = n.indexOf("/Date(") > -1 ? new Date(parseInt(n.replace("/Date(", "").replace(")/", ""),
		10)) : new Date(Date.parse(n.replace(/-/g, "/").replace("T", " ").split(".")[0])));
	r = {
		"M+": i.getMonth() + 1,
		"d+": i.getDate(),
		"h+": i.getHours(),
		"m+": i.getMinutes(),
		"s+": i.getSeconds(),
		"q+": Math.floor((i.getMonth() + 3) / 3),
		S: i.getMilliseconds()
	};
	/(y+)/.test(t) && (t = t.replace(RegExp.$1, (i.getFullYear() + "").substr(4 - RegExp.$1.length)));
	for (u in r) new RegExp("(" + u + ")").test(t) && (t = t.replace(RegExp.$1, RegExp.$1.length == 1 ? r[u] : ("00" +
		r[u]).substr(("" + r[u]).length)));
	return t
}
// "yyyy-MM-dd hh:mm:sss"

// 格式化日期，如月、日、时、分、秒保证为2位数
function formatNumber (n) {
    n = n.toString()
    return n[1] ? n : '0' + n;
}
// 参数number为毫秒时间戳，format为需要转换成的日期格式
function formatTimes (number, format) {
    let time = new Date(number * 1000)
    let newArr = []
    let formatArr = ['Y', 'M', 'D', 'h', 'm', 's']
    newArr.push(time.getFullYear())
    newArr.push(formatNumber(time.getMonth() + 1))
    newArr.push(formatNumber(time.getDate()))

    newArr.push(formatNumber(time.getHours()))
    newArr.push(formatNumber(time.getMinutes()))
    newArr.push(formatNumber(time.getSeconds()))

    for (let i in newArr) {
        format = format.replace(formatArr[i], newArr[i])
    }
    return format;
}

function getToken() {
	if (uni.getStorageSync("token")) {
		return uni.getStorageSync("token");
	} else {
		return "";
	}
}
// 获取更新的token
function getnewToken(){
	
}

// 将数据插入每个接口
function phoneMsg(){
	if (uni.getStorageSync("application_client_type")) {
		let phone = uni.getStorageSync("application_client_type")
		// application=app&application_client_type
		return '?application=app&application_client_type='+phone
	} else {
		return "?application=app&application_client_type=android";
	}
}

function Percentage(ab) {
	var data = parseInt(ab * 100);
	console.log(data);
	return data
}
// 函数的截流
function throttle(fn, gapTime) {
    if (gapTime == null || gapTime == undefined) {
        gapTime = 1500
    }

    let _lastTime = null

    // 返回新的函数
    return function () {
        let _nowTime = + new Date()
        if (_nowTime - _lastTime > gapTime || !_lastTime) {
            fn.apply(this, arguments)   //将this和参数传给原函数
            _lastTime = _nowTime
        }
    }
}
function getUrl() {
	return 'https://app.wisili.com/index.php/api/'
}
function getIndexUrl() {
	return 'https://app.wisili.com/index.php/index/'
}

// 不需要token的
function fech(url, postData, succ, fail) {
	let header = {}
	uni.request({ 
		url: getUrl() + url,
		data: postData,
		dataType: 'json',
		method: 'POST',
		header,
		success: function(data) {
			// console.log(JSON.stringify(data));
			succ(data.data)
		},
		fail: function(data) {
			console.log(JSON.stringify(data));
			uni.hideLoading()
			setTimeout(function() {
				uni.showToast({
					icon: 'none',
					title: '网络连接出错，请重试',
					duration: 3000
				});
			}, 100)
		}
	})
}

function postAjax(url, postData, succ, fail) {
	let header = {}
	let phoneType = phoneMsg()
	header['token'] = getToken()
	uni.request({ 
		url: getUrl() + url+phoneType,
		data: postData,
		dataType: 'json',
		method: 'POST',
		header,
		success: function(data) {
			// console.log(JSON.stringify(data));
			succ(data.data)
		},
		fail: function(data) {
			fail(data.data)
		}
	})
}
function getAjaxj(url, postData, succ, fail) {
	uni.request({
		url:url,
		data: postData,
		dataType: 'json',
		method: 'GET',
		success: function(data) {
			// console.log(JSON.stringify(data));
			succ(data.data)
		},
		fail: function(data) {
			console.log(JSON.stringify(data));
			uni.hideLoading()
			setTimeout(function() {
				uni.showToast({
					icon: 'none',
					title: '网络连接出错，请重试',
					duration: 3000
				});
			}, 100)
		}
	})
}
function getAjax(url, postData, succ, fail) {
	uni.request({
		url: getUrl() + url,
		data: postData,
		dataType: 'json',
		method: 'GET',
		success: function(data) {
			// console.log(JSON.stringify(data));
			succ(data.data)
		},
		fail: function(data) {
			console.log(JSON.stringify(data));
			uni.hideLoading()
			setTimeout(function() {
				uni.showToast({
					icon: 'none',
					title: '网络连接出错，请重试',
					duration: 3000
				});
			}, 100)
		}
	})
}

function getAjaxx(url, postData, action, succ, fail) {
	var data1 = formatDate(new Date(), "yyyy-MM-dd hh:mm:sss");
	let time1 = new Date(Date.parse(data1.replace(/-/g, "/"))).getTime();
	let date = time1 / 1000; //精确到秒就可以了，再除以1000即可
	// console.log( getToken())
	// console.log(date)
	// console.log(getUrl())
	uni.request({
		url: getUrl() + url,
		data: postData,
		dataType: 'json',
		method: 'POST',
		header: {
			token: getToken(),
			action: action,
			format: 'json',
			charset: 'utf-8',
			version: '1.0',
			timestamp: date
		},
		success: function(data) {
			// console.log(JSON.stringify(data));
			succ(data.data)
		},
		fail: function(data) {
			console.log(JSON.stringify(data));
			uni.showToast({
				icon: 'none',
				title: '网络连接出错，请重试'
			});
		}
	})
}

function wsCmd(action, userinfo, vehid, pram, callback) {

	console.log("连接信息" + JSON.stringify(userinfo));
	//实例化
	var ws = mysocket(userinfo, function(res) {
		callback(res);
		console.log(res);
	});
	mysocket[0].page.analysis(action, vehid, pram);

	// 	
	// 	setTimeout(function() {
	// 		mysocket.page.analysis(action, vehid, pram);
	// 	}, 2000)
}

function uploadIMG(url, imgs, succ) {
	let header = {}
	header['token'] = getToken()
	uni.uploadFile({
		url: getUrl() + url,
		filePath: imgs,
		name: 'files',
		header,
		formData: {
			files: imgs
		},
		success: function(uploadFileRes) {
			succ(uploadFileRes);
		},
		fail: function(data) {
			console.log("失败" + JSON.stringify(data));
			uni.showToast({
				icon: 'none',
				title: '网络连接出错，请重试'
			});
		}
	});
}
function uploadIMGS(url, imgs, succ) {
	let token = getToken()
	uni.uploadFile({
		url: getUrl() + url,
		filePath: imgs,
		name: 'upfile',
		header:{"Content-Type": "multipart/form-data"},
		success: function(uploadFileRes) {
			succ(uploadFileRes);
		},
		fail: function(data) {
			console.log("失败" + JSON.stringify(data));
			uni.showToast({
				icon: 'none',
				title: '网络连接出错，请重试'
			});
		}
	});
}
function addUserInfo(userInfo) {
	let users = {
		account: userInfo.account,
		password: userInfo.password
	};
	uni.setStorageSync('cwg_userInfos', JSON.stringify(users));
}

function getUserInfo() {
	let ret = uni.getStorageSync('cwg_userInfos');
	if (!ret) {
		ret = false;
	}
	return JSON.parse(ret);
}

function log(msg) {
	if (store.state.debug) {
		// console.log(JSON.stringify(msg))
	}
}

function formatTime(time) {
	if (typeof time !== 'number' || time < 0) {
		return time
	}

	var hour = parseInt(time / 3600)
	time = time % 3600
	var minute = parseInt(time / 60)
	time = time % 60
	var second = time

	return ([hour, minute, second]).map(function(n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}).join(':')
}

function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}
//获取个推clientid
function client() {
	var id = '';
	uni.getProvider({
		service: 'push',
		success: function(res) {
			// console.log(res.provider)
			// 个推的名称为 igexin
			uni.subscribePush({
				provider: 'igexin',
				success: function(res) {
					id = res.clientid
					// console.log('success:' + JSON.stringify(res));
				}
			});
		}
	});
	return id
}

function forMatNum(num) {
	return num < 10 ? '0' + num : num + '';
}
function deepCopy(obj){
	  var result = Array.isArray(obj) ? [] : {};
	  for (var key in obj) {
		if (obj.hasOwnProperty(key)) {
		  if (typeof obj[key] === 'object' && obj[key]!==null) {
			result[key] = deepCopy(obj[key]);   //递归复制
		  } else {
			result[key] = obj[key];
		  }
		}
	  }
	  return result;
}
function initDays(year, month) {
	let totalDays = new Date(year, month, 0).getDate();
	let dates = [];
	for (let d = 1; d <= totalDays; d++) {
		dates.push(forMatNum(d));
	};
	return dates;
}

function initPicker(start, end, mode = "date", step = 1) {
	let initstartDate = new Date(start);
	let endDate = new Date(end);
	let startYear = initstartDate.getFullYear();
	let startMonth = initstartDate.getMonth();
	let endYear = endDate.getFullYear();
	let years = [],
		months = [],
		days = [],
		hours = [],
		minutes = [];
	let totalDays = new Date(startYear, startMonth, 0).getDate();
	for (let s = startYear; s <= endYear; s++) {
		years.push(s + '');
	};
	for (let m = 1; m <= 12; m++) {
		months.push(forMatNum(m));
	};
	for (let d = 1; d <= totalDays; d++) {
		days.push(forMatNum(d));
	}
	for (let h = 0; h < 24; h++) {
		hours.push(forMatNum(h));
	}
	for (let m = 0; m < 60; m += step) {
		minutes.push(forMatNum(m));
	}
	if (mode == "date") {
		return {
			years,
			months,
			days
		}
	} else if (mode == "dateTime") {
		return {
			years,
			months,
			days,
			hours,
			minutes
		}
	} else if (mode == "time") {
		return {
			hours,
			minutes
		}
	}
}

var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function(milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function(dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function(number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDay()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function(str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	}
};

module.exports = {
	formatTime: formatTime,
	formatLocation: formatLocation,
	dateUtils: dateUtils,
	getAjax: getAjax,
	postAjax: postAjax,
	getAjaxx: getAjaxx,
	getAjaxj:getAjaxj,
	getToken: getToken,
	phoneMsg:phoneMsg,
	log: log,
	getUserInfo: getUserInfo,
	addUserInfo: addUserInfo,
	getQueryString: getQueryString,
	uploadIMG: uploadIMG,
	formatDate: formatDate,
	updateApp: updateApp,
	wsCmd: wsCmd,
	client: client,
	forMatNum: forMatNum,
	initDays: initDays,
	initPicker: initPicker,
	getUrl: getUrl,
	formatTimes:formatTimes,
	fech:fech,
	deepCopy:deepCopy,
	handleClipboard:handleClipboard,
	throttle:throttle,
	uploadIMGS:uploadIMGS,
	getIndexUrl:getIndexUrl
}
